package com.notice.view;

import com.notice.model.UserModel;
import com.notice.viewmodel.UserViewModel;
import com.notice.util.ResponseUtil;
import com.notice.common.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import java.util.Observable;
import java.util.Observer;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/User")
@CrossOrigin
public class UserView implements Observer {

    @Autowired
    private UserViewModel userViewModel;
    
    @PostConstruct
    public void init() {
        userViewModel.addObserver(this);
    }

    @PostMapping("/Login")
    @ResponseBody
    public ResponseEntity<?> login(@RequestBody UserModel user) {
        userViewModel.login(user.getUid(), user.getPassword());
        UserModel currentUser = userViewModel.getCurrentUser();
        if(currentUser != null) {
            Map<String, Integer> response = new HashMap<>();
            response.put("utype", currentUser.getUtype());
            return ResponseUtil.success(response);
        }
        return ResponseUtil.error(Constants.ErrorCodes.LOGIN_FAIL, Constants.Messages.LOGIN_FAIL);
    }

    @PostMapping("/Add")
    @ResponseBody
    public ResponseEntity<?> addUser(@RequestBody UserModel user) {
        if (userViewModel.register(user)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.LOGIN_FAIL, Constants.Messages.USER_EXISTS);
    }

    @GetMapping("/getAll")
    @ResponseBody
    public ResponseEntity<?> getAllUsers() {
        return ResponseUtil.success(userViewModel.getAllUsers());
    }

    @PostMapping("/Delete/{uid}")
    @ResponseBody
    public ResponseEntity<?> deleteUser(@PathVariable String uid) {
        if (userViewModel.deleteUser(uid)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.DELETE_FAIL, Constants.Messages.USER_NOT_EXISTS);
    }

    @PostMapping("/Update")
    @ResponseBody
    public ResponseEntity<?> updateUser(@RequestBody UserModel user) {
        if (userViewModel.updateUser(user)) {
            return ResponseUtil.success();
        }
        return ResponseUtil.error(Constants.ErrorCodes.UPDATE_FAIL, Constants.Messages.UPDATE_FAIL);
    }
    
    @Override
    public void update(Observable o, Object arg) {
        // 处理 ViewModel 的状态更新
    }
} 